/*
有一个正整数数组 arr，现给你一个对应的查询数组 queries，其中 queries[i] = [Li, Ri]。

对于每个查询 i，请你计算从 Li 到 Ri 的 XOR 值（即 arr[Li] xor arr[Li+1] xor ... xor arr[Ri]）作为本次查询的结果。

并返回一个包含给定查询 queries 所有结果的数组。

 

示例 1：

输入：arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
输出：[2,7,14,8] 
解释：
数组中元素的二进制表示形式是：
1 = 0001 
3 = 0011 
4 = 0100 
8 = 1000 
查询的 XOR 值为：
[0,1] = 1 xor 3 = 2 
[1,2] = 3 xor 4 = 7 
[0,3] = 1 xor 3 xor 4 xor 8 = 14 
[3,3] = 8
示例 2：

输入：arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
输出：[8,0,4,4]
 

提示：

1 <= arr.length <= 3 * 10^4
1 <= arr[i] <= 10^9
1 <= queries.length <= 3 * 10^4
queries[i].length == 2
0 <= queries[i][0] <= queries[i][1] < arr.length

*/

#include "stdc++.h"

// 暴力，超时
class Solution {
public:
    vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
        int n = queries.size();
        vector<int> res(n, 0);
        for (int i{0}; i < n; ++i) {
            int L = queries[i][0];
            int R = queries[i][1];
            for (int j{L}; j <= R; ++j) {
                res[i] ^= arr[j];
            }
        }
        return res;
    }
};

// 缓存前缀和
class Solution {
public:
    vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
        // 记录 [0, i] 的 XOR 值
        int m = arr.size();
        vector<int> record(m, 0);
        record[0] = arr[0];
        for (int i{1}; i < m; ++i) {
            record[i] = record[i-1] ^ arr[i];
        }

        int n = queries.size();
        vector<int> res(n, 0);
        for (int i{0}; i < n; ++i) {
            int L = queries[i][0];
            int R = queries[i][1];
            if (L == 0) {
                res[i] = record[R];
            } else {
                res[i] = record[L-1] ^ record[R];
            }
        }
        return res;
    }
};

// 缓存前缀和
class Solution {
public:
    vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
        // record[i] = [0, i-1] 的 XOR 值
        int m = arr.size();
        vector<int> record(m+1, 0);
        for (int i{0}; i < m; ++i) {
            record[i+1] = record[i] ^ arr[i];
        }

        int n = queries.size();
        vector<int> res(n, 0);
        for (int i{0}; i < n; ++i) {
            int L = queries[i][0];
            int R = queries[i][1];
            res[i] = record[L] ^ record[R+1];
        }
        return res;
    }
};
